# -*- coding: UTF-8 -*-
import os

from pyramid.view import view_config, forbidden_view_config
from pyramid.response import Response
from pyramid.renderers import render_to_response
from pyramid.httpexceptions import HTTPNotFound

from ..freedom.captcha.captcha import process_request
from ..lib.utils import upload

from ..models.meta import (
    DBSession,
    )

from ..models.models import *

#----------------- forbidden view --------------------------------
@forbidden_view_config()
def forbidden(request):
    referrer = ''
    if request.path.find('/admin/') >=0:
        referrer = request.route_url('admin_login')
    if request.path.find('/business/') >=0:
        referrer = request.route_url('business_login')
    referrer = referrer or request.referrer

    tmpl_context = {'referrer': referrer}
    return render_to_response('/admin/forbidden.html', tmpl_context, request = request)

#----------------- 404 view --------------------------------
@view_config(context=HTTPNotFound)
def not_found(self, request):
    request.response.status = 404
    return render_to_response('/admin/404.html', {}, request = request)

#----------------- captcha view --------------------------------
@view_config(route_name='captcha')
def captcha_create(request):
    code, out = process_request()
    request.session['CONSTANT_Captcha'] = code
    Response.content_type = 'image/gif'
    return Response(out.read())

#----------------- validation view --------------------------------
@view_config(route_name='validation1')
@view_config(route_name='validation2')
def validation(request):
    (model, column, rule) = request.params.get('fieldId').split('_')
    value = request.params.get('fieldValue')

    tmpl_context = []

    if(rule == 'unique'):
        exec """
tmpl_context = [request.params.get('fieldId'), DBSession().query(%s).filter(%s.%s == '%s').count() == 0]
        """ % (model, model, column, value)

    return render_to_response('json', tmpl_context, request = request)

@view_config(route_name='validationSubmit')
def validationSubmit(request):
    tmpl_context = []
    result = []
    #get validation info
    validationFields = dict((key.replace('validation_',''), value) for (key, value) in request.params.items() if key.find('validation_') ==0)
    for (key, value) in validationFields.items():
        (model, column, rule) = value.split('_')
        if(rule == 'unique'):
            exec """
result = [value, DBSession().query(%s).filter(%s.%s == '%s').count() == 0, '%s']
            """ % (model, model, column, request.params.get(key), u'* 此名称已被其他人使用')
    if result:
        tmpl_context.append(result)
    return render_to_response('json', tmpl_context, request = request)


@view_config(route_name='ueditor_php')
def ueditor_php(request):
    path = request.matchdict.get('path')
    if(path == 'imageManager'):
        return ueditor_imageManager(request)
    if(path == 'imageUp'):
        return ueditor_imageUp(request)

def ueditor_imageManager(request):
    upload = 'upload'
    upload_path = os.path.join(request.registry.settings.get('upload.root') + upload)
    filetype = (".gif", ".png", ".jpg", ".jpeg", ".bmp")                #文件允许格式
    result = ''
    if(request.params.get('action')=='get'):
        for root, dirs, files in os.walk(upload_path):
            for f in files:
                result += os.path.join(upload, f + 'ue_separate_ue')
    return Response(result)

def ueditor_imageUp(request):
    upload_path = os.path.join(request.registry.settings.get('upload.root') + 'upload')
    size = 2 #upload file size < 2M
    filetype = (".gif", ".png", ".jpg", ".jpeg", ".bmp")                #文件允许格式
    uploadfilename = upload(request.params.get('upfile'), upload_path, filetype, size)

    result = {
            'url':'upload/' + uploadfilename.encode('utf8'),
            'title':request.params.get('pictitle').encode('utf8'),
            'original':request.params.get('fileName').encode('utf8'),
            'state':'SUCCESS'
            }
    return Response(str(result))
